/**
 * Created by lvzj on 2015/6/16.
 */
var toolUtil = require('../../common/utils/toolUtil');
var mysqlUtil = require('../../common/utils/mysqlUtil');
var users = mongoose.model('user');
var replyAtService = mongoose.model('question_replyAtService');
var async = require('async');
var replyAt = mongoose.model('question_replyAt');
var NeighbourActivity = mongoose.model('activity_neighbour');
var Question = mongoose.model('question');
var SpecialTopics = mongoose.model('system_specialTopics');
var session = require('express-session');

exports.getAtCsList = function (input, callback) {

    var currentPage = 1;
    if (input.currentPage != '' && input.currentPage != null) {
        currentPage = input.currentPage;
    }
    var pageSize = 10;
    var offset = (currentPage - 1) * pageSize;

    var communityId = input.communityId;
    var status = input.status;

    var condition = {};

    if (communityId != null && communityId != '') {
        condition.community = communityId;
    }
    if (status != null) {
        condition.status = status;
    }


    async.series([

        function (callbackInner) {
            replyAtService.find(condition).skip(offset).limit(pageSize).populate('atUser', 'nickName').populate('community', 'communityName')
                .sort('-dateCreated').exec(function (err, result) {
                    if (result != null) {
                        async.each(result, function (temp, callbackInner) {
                            replyAt.findOne({replyId: temp._doc.replyId + ''}, function (err, at) {
                                if (at != null && at.uList != null) {
                                    at.uList.forEach(function (u, i) {
                                        if (temp._doc.content != null)
                                            temp._doc.content = temp._doc.content.replace(new RegExp("@\\{" + i + "\\}"), '@' + u.nickName + ' ')
                                    });
                                }
                                callbackInner();
                            }).populate('uList', '_id nickName');
                        }, function (err) {
                            callbackInner(err, result);
                        })
                    } else {
                        callbackInner(err, result);
                    }
                });
        },
        function (callbackInner) {
            replyAtService.count(condition, function (err, result) {
                var totalPage = 0;
                if (result != null) {
                    var count = result;
                    var totalPage = Math.ceil(count / pageSize);
                }
                callbackInner(err, totalPage);
            });
        }
    ], callback)

};

exports.updateAtCsUpdate = function (input, callback) {

    var id = input.id;

    replyAtService.update({'_id': id}, {'status': false}, callback);

};

exports.getSharedFeeds = function (contentId, category, userId, callback) {
    var typeName = {
        qst: "question",
        act: "neighbourActivity",
        top: "topic"

    }
    var atFlag = '@';
    switch (category) {
        case typeName.qst:
            exports.getQuestion(contentId, function (err, qstObj) {
                if (err) {
                    callback(err, null);
                }
                qstObj._doc['type'] = 1;
                qstObj._doc['categoryName'] = questionCategory[qstObj.category];
                qstObj._doc['titleDesc'] = '小区邻居发起的';
                qstObj._doc['replyCount'] = qstObj.replies.length;
                qstObj._doc['dateCreated'] = qstObj.dateCreated.getTime();
                qstObj._doc.createdBy._doc.images = qstObj.createdBy.images[0].imageURL.indexOf('http') == 0 ? qstObj.createdBy.images[0].imageURL : fastDfsHostIp + qstObj.createdBy.images[0].imageURL;

                var replies = [];
                if (qstObj.replies != null && qstObj.replies.length > 0) {
                    replies = qstObj.replies;
                }
                var data = [];
                async.eachSeries(replies, function (temp, callbackInner) {
                    if (temp.replyDesc != null && temp.replyDesc.indexOf(atFlag) != -1) {
                        replyAt.findOne({replyId: temp._id + ''}, function (err, at) {
                            if (at != null && at.uList != null) {
                                at.uList.forEach(function (user, i) {
                                    temp.replyDesc = temp.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + user.nickName + ' ')
                                });
                            }
                            var a = {
                                nickName: temp.repliedBy.nickName,
                                images: temp.repliedBy.images[0].imageURL.indexOf('http') == 0 ? temp.repliedBy.images[0].imageURL : fastDfsHostIp + temp.repliedBy.images[0].imageURL,
                                replyDesc: temp.replyDesc,
                                replyDate: temp.dateReplied.getTime()
                            };
                            data.push(a);
                            callbackInner()
                        }).populate('uList', '_id nickName');
                    } else if (temp.replyDesc != null && temp.replyDesc != '') {
                        var a = {
                            nickName: temp.repliedBy.nickName,
                            images: temp.repliedBy.images[0].imageURL.indexOf('http') == 0 ? temp.repliedBy.images[0].imageURL : fastDfsHostIp + temp.repliedBy.images[0].imageURL,
                            replyDesc: temp.replyDesc,
                            replyDate: temp.dateReplied.getTime()
                        };
                        data.push(a);
                        callbackInner(err);
                    } else {
                        callbackInner()
                    }
                }, function (err) {
                    qstObj._doc['replies'] = data;

                    callback(null, {obj: qstObj, "host": fastDfsHostIp});
                });
            });
            break;
        case typeName.act:
            exports.getNeighbourActivity(contentId, function (err, actObj) {
                actObj._doc['type'] = 2;
                actObj._doc['categoryName'] = '邻里活动';
                actObj._doc['titleDesc'] = '小区邻居发起的';

                actObj._doc['dateCreated'] = actObj.dateCreated.getTime();
                if (actObj.deadline != null)
                    actObj._doc.deadline = actObj._doc.deadline.getTime();
                actObj._doc['replyCount'] = actObj.replies.length;
                actObj._doc.createdBy._doc.images = actObj.createdBy.images[0].imageURL.indexOf('http') == 0 ? actObj.createdBy.images[0].imageURL : fastDfsHostIp + actObj.createdBy.images[0].imageURL;

                var replies = [];
                if (actObj.replies != null && actObj.replies.length > 0) {
                    replies = actObj.replies
                }
                var data = [];

                async.eachSeries(replies, function (temp, callbackInner) {
                    if (temp.replyDesc != null && temp.replyDesc.indexOf(atFlag) != -1) {
                        replyAt.findOne({replyId: temp._id + ''}, function (err, at) {
                            if (at != null && at.uList != null) {
                                at.uList.forEach(function (user, i) {
                                    temp.replyDesc = temp.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + user.nickName + ' ')
                                });
                            }
                            var a = {
                                nickName: temp.repliedBy.nickName,
                                images: temp.repliedBy.images[0].imageURL.indexOf('http') == 0 ? temp.repliedBy.images[0].imageURL : fastDfsHostIp + temp.repliedBy.images[0].imageURL,
                                replyDesc: temp.replyDesc,
                                replyDate: temp.dateReplied.getTime()
                            };
                            data.push(a);
                            callbackInner()
                        }).populate('uList', '_id nickName');
                    } else if (temp.replyDesc != null && temp.replyDesc != '') {
                        var a = {
                            nickName: temp.repliedBy.nickName,
                            images: temp.repliedBy.images[0].imageURL.indexOf('http') == 0 ? temp.repliedBy.images[0].imageURL : fastDfsHostIp + temp.repliedBy.images[0].imageURL,
                            replyDesc: temp.replyDesc,
                            replyDate: temp.dateReplied.getTime()
                        };
                        data.push(a);
                        callbackInner(err);
                    } else {
                        callbackInner()
                    }
                }, function (err) {
                    actObj._doc['replies'] = data;

                    var number = 0;
                    actObj.partake.forEach(function (par) {
                        number += par.number;
                    });

                    actObj._doc['number'] = number;
                    var array = actObj.partake;

                    actObj._doc['partakeNum'] = actObj.partake.length;
                    var partake = [];
                    array.forEach(function (temp) {

                        if (temp.partakeType == 2) {
                            temp._doc.user = {
                                nickName: temp.name,
                                images: [{imageURL: wechatImage}]
                            }
                        }
                        var b = {
                            _id: temp.user._id,
                            nickName: temp.user.nickName,
                            images: temp.user.images[0].imageURL.indexOf('http') == 0 ? temp.user.images[0].imageURL : fastDfsHostIp + temp.user.images[0].imageURL,
                            number: temp.number,
                            date: temp.time.getTime()
                        };
                        partake.push(b);
                    });

                    actObj._doc['partake'] = partake;
                    callback(null, {obj: actObj, "host": fastDfsHostIp});
                });
            });
            break;
        case typeName.top:
            exports.getSpecialTopic(contentId, function (err, topObj) {
                topObj._doc['type'] = 3;
                topObj._doc['categoryName'] = '专题';
                topObj._doc['titleDesc'] = '推荐的有趣';
                topObj._doc['dateCreated'] = topObj.dateCreated.getTime();
                callback(null, {obj: topObj, "host": fastDfsHostIp});
            });
            break;
    }
    ;
}

exports.getNeighbourActivity = function (activityId, callback) {
    NeighbourActivity.findOne({_id: activityId}, 'title desc category images replies partake browserCount community dateCreated createdBy activityType deadline', callback).populate("community", "communityName").populate('replies.repliedBy', 'nickName images').populate('partake.user', 'nickName images').populate('createdBy', 'nickName images')
}

exports.getQuestion = function (questionId, callback) {
    Question.findOne({_id: questionId}, 'desc category images replies browserCount community dateCreated createdBy', callback).populate("community", "communityName").populate('replies.repliedBy', 'nickName images').populate('createdBy', 'nickName images')
}

exports.getSpecialTopic = function (topicId, callback) {
    SpecialTopics.findOne({_id: topicId}, callback);
}